package kr.ac.iislab.tbrobot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OutputSort {

	public static void sort( String filename ) {
		String[] pre = new String[4];
		ArrayList<Result> resultList = new ArrayList<Result>();
		int preCnt = 0;
		int nonCnt = 0;
		
		FileReader fr;
		try {
			fr = new FileReader( filename );
			BufferedReader inFile = new BufferedReader( fr );
			
			while( preCnt < 4 )	{
				pre[preCnt] = inFile.readLine();
				preCnt++;
			}
			
			String line = inFile.readLine();
			
			if( line == null )	{
				System.err.println( filename + " has no text!!!" );
				System.exit(0);
			}
			
			Pattern pagelink = Pattern.compile( ":[ ]+([0-9]+.[0-9]+)", Pattern.CASE_INSENSITIVE );
			Matcher m = pagelink.matcher( line );
			
			while( line != null )	{
				if( m.find() )	{
					Result result = new Result( line );
					result.setScore( Double.parseDouble(m.group(1)) );
					resultList.add( result );
				}
				else	{
					nonCnt++;
				}

				line = inFile.readLine();
				line = inFile.readLine();
				if( line != null )	m = pagelink.matcher( line );
			}

			ArrayList<Result> sortedList = sortResult( resultList );
			
			FileWriter fw;
			if( !TBRobot.DEBUG )	{
				fw = new FileWriter( filename.replace(".log", "_sorted.log") );
			}
			else	{
				fw = new FileWriter( filename.replace(".log", "_sorted_test.log") );
			}

			BufferedWriter bw = new BufferedWriter( fw );
			PrintWriter outFile = new PrintWriter( bw );
			
			outFile.println( pre[0] );
			outFile.println( pre[1] );
			outFile.println( pre[2] );
			outFile.println( pre[3] );
			outFile.println( "" );
			
			int cnt = 0;
			for (Iterator<Result> iterator = sortedList.iterator(); iterator.hasNext();) {
				cnt++;
				Result result = (Result) iterator.next();
				outFile.println( cnt + ": " + result.getTag() );
				outFile.println( "" );
			}
			outFile.close();
			System.out.println( "None pattern: " + nonCnt );
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static ArrayList<Result> sortResult( ArrayList<Result> list )	{
		Collections.sort( list, new Comparator<Object>()	{
			public int compare( Object o1, Object o2 )	{
				return ((Result)o2).getScore().compareTo( ((Result)o1).getScore() );
			}
		} );
		
		return list;
	}
}
